package cn.turboinfo.fuyang.api.domain.admin.usecase.account;

import cn.turboinfo.fuyang.api.domain.common.service.account.CompanyAccountService;
import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.account.CompanyAccount;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import com.alibaba.excel.EasyExcel;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class CompanyAccountExportUseCase extends AbstractUseCase<CompanyAccountExportUseCase.InputData, CompanyAccountExportUseCase.OutputData> {
    private final CompanyAccountService companyAccountService;

    private final HousekeepingCompanyService housekeepingCompanyService;

    @Override
    protected OutputData doAction(InputData inputData) {

        List<Long> idList = inputData.getIdList();
        HttpServletResponse response = inputData.getResponse();

        List<CompanyAccount> companyAccountList = companyAccountService.findByIdCollection(idList);

        Set<Long> companyIdSet = companyAccountList.stream()
                .map(CompanyAccount::getCompanyId)
                .collect(Collectors.toSet());
        Map<Long, String> companyMap = housekeepingCompanyService.findByIdCollection(companyIdSet)
                .stream()
                .collect(Collectors.toMap(HousekeepingCompany::getId, HousekeepingCompany::getName));

        companyAccountList.stream().peek(it -> it.setCompanyName(companyMap.get(it.getCompanyId()))).toList();

        try {
            EasyExcel.write(response.getOutputStream(), CompanyAccount.class)
                    .sheet("账号列表")
                    .doWrite(companyAccountList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return OutputData.builder()
                .response(response)
                .build();
    }


    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {
        @NotNull(
                message = "id编码列表不能为空"
        )
        private List<Long> idList;

        @NotNull
        private HttpServletResponse response;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private HttpServletResponse response;
    }
}
